package org.lottery.activity;

import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.widget.Toast;

public class SettingsActivity extends PreferenceActivity {

    public static final String SETTINGS_REWARD_QUANTITY = "settings_reward_quantity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .replace(android.R.id.content, new SettingsFragment())
                    .commit();
        }
    }

    public static class SettingsFragment extends PreferenceFragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings);

            findPreference("settings_reward_quantity").setOnPreferenceChangeListener(
                    new Preference.OnPreferenceChangeListener() {

                        @Override
                        public boolean onPreferenceChange(Preference preference, Object newValue) {

                            boolean valid = false;
                            try {
                                if (1 <= Integer.parseInt(newValue + "") && Integer.parseInt(newValue + "") <= 9) {
                                    valid = true;
                                } else {
                                    Toast.makeText(getActivity(), "Error could not save setting, valid input is number from 1-9", Toast.LENGTH_LONG).show();
                                }
                            } catch (Exception e) {
                                Toast.makeText(getActivity(), "Error could not save setting, valid input is number from 1-9", Toast.LENGTH_LONG).show();
                            }
                            if (valid)
                                Toast.makeText(getActivity(), "Save successed", Toast.LENGTH_LONG).show();
                            return valid;
                        }

                    });
        }
    }
}
